import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'JuBoConfig.dart';

// dio 请求
class JuBoHttpRequest {

    static final BaseOptions baseOptions = BaseOptions(
        baseUrl: HttpConfig.baseUrl,
        connectTimeout: HttpConfig.timeout,
        contentType: Headers.jsonContentType,

    );

    static final Dio dio = Dio(baseOptions);
    static Future<T> request<T>(String url, {
                      String method = "get",
                      Map<String, dynamic> params,
                      Interceptor inter}) async {



    // 1.创建单独配置
    final options = Options(
        method: method,
     );

    // 全局拦截器
    // 创建默认的全局拦截器
    Interceptor dInter = InterceptorsWrapper(
        onRequest: (Options options) {
          return options;
        },
        onResponse: (response) {
          print("响应拦截");
          return response;
        },
        onError: (err) {
          print("错误拦截");
          print(err.response.headers);
          return err;
        }
    );
    List<Interceptor> inters = [dInter];

    // 请求单独拦截器
    if (inter != null) {
      inters.add(inter);
    }

    // 统一添加到拦截器中
    dio.interceptors.addAll(inters);

    // 2.发送网络请求
    try {
      Response response = await dio.request(url, queryParameters: params, options: options);
      return response.data;
    } on DioError catch(e) {
      return Future.error(e);
    }
  }
}

// 原生请求
class JuBoHttpNativeRequest {

  static Future<T> nativeRequest<T>(String url, {
    Map<String, dynamic> params,
    Interceptor inter}) async {

      final uri = HttpConfig.baseUrl + url;
      HttpClient httpClient = HttpClient();
      HttpClientRequest request = await httpClient.postUrl(Uri.parse(uri));
      request.headers.add('Content-Type', 'application/json');

      if(params!=null){
        request.add(utf8.encode(json.encode(params)));
      }

      HttpClientResponse response = await request.close();
      final result = await response.transform(Utf8Decoder()).join() ;
      httpClient.close();
      final resultJson = json.decode(result);
      return resultJson;
  }
}

